package stpmproject.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import stpmproject.controller.viewobject.ProjectVO;
import stpmproject.error.BusinessException;
import stpmproject.error.EmBusinessError;
import stpmproject.response.CommonReturnType;
import stpmproject.service.ProjectService;
import stpmproject.service.model.ProjectModel;
import stpmproject.service.model.UserModel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.List;
import java.util.stream.Collectors;

/**
 * encoding: utf-8
 *
 * @Author: kou dui
 * @Date: 2019/5/21 20:23
 * @software: IntelliJ IDEA
 * @file: ProjectController
 * @description:
 */
//@Controller 表明这个类是一个控制器类，和@RequestMapping来配合使用拦截请求，
// 如果不在method中注明请求的方式，默认是拦截get和post请求
@Controller("project")
@RequestMapping("/project")
@CrossOrigin(allowedHeaders = {"*"},allowCredentials = "true") //springboot前端请求的跨域问题
public class ProjectController extends BaseController{
    @Autowired
    private ProjectService projectService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @RequestMapping("/get")
    @ResponseBody
    public CommonReturnType getProject(@RequestParam(name = "id") Integer projectId) throws BusinessException {
        ProjectModel projectModel=projectService.getProjectById(projectId);
        if(projectModel==null){
            throw new BusinessException(EmBusinessError.PROJECT_NOT_EXIST);
        }
        ProjectVO projectVO=convertVOFromModel(projectModel);
        return CommonReturnType.create(projectVO);
    }

    private ProjectVO convertVOFromModel(ProjectModel projectModel){
        if(projectModel==null){
            return null;
        }
        ProjectVO projectVO=new ProjectVO();
        BeanUtils.copyProperties(projectModel,projectVO);
        projectVO.setProjectEndDate(projectModel.getProjectEndDate().toDate());
        projectVO.setProjectStartDate(projectModel.getProjectStartDate().toDate());
        //日期处理
        DateTime nowDate=DateTime.now();
//        System.out.println("nowDate = " + nowDate);
        DateTime startDate=new DateTime(projectModel.getProjectStartDate());
//        System.out.println("startDate = " + startDate);
        DateTime endDate=new DateTime(projectModel.getProjectEndDate());
//        System.out.println("endDate = " + endDate);
        if(nowDate.isAfter(startDate) && projectVO.getProjectStatus().equals("未开始")){
            projectVO.setProjectStatus("已延期");
        }
        int usedHours=0;
        projectVO.setUsedHours(usedHours+"");
        if(projectVO.getProjectStatus().equals("进行中")){
            usedHours=(Days.daysBetween(startDate,nowDate).getDays())*projectVO.getHours();
            projectVO.setUsedHours(usedHours+"");
        }
        //开始时间和结束时间相差的天数作为总的工时
        int totalHours=(Days.daysBetween(startDate,endDate).getDays())*projectVO.getHours();
        if(projectVO.getProjectStatus().equals("已完成")){
            usedHours=totalHours;
            projectVO.setUsedHours(usedHours+"");
        }
        projectVO.setTotalHours(totalHours+"");
        //获取剩下的工时
        projectVO.setLeftHours((totalHours-usedHours)+"");
        //进度，两位小数显示
        DecimalFormat df=new DecimalFormat("0.00");
        if(totalHours==0){
            projectVO.setProjectProcess("100.00");
        }
        else{
            projectVO.setProjectProcess(df.format((float)(usedHours*100/totalHours)));
        }
        return projectVO;
    }

    //创建项目接口
    @RequestMapping(value = "/create",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType createProject(@RequestParam(name = "projectName") String projectName,
                                          @RequestParam(name = "projectCode") String projectCode,
                                          @RequestParam(name = "projectPriority") String projectPriority,
                                          @RequestParam(name = "projectKeyword") String projectKeyword,
                                          @RequestParam(name = "projectStartDate") String projectStartDate,
                                          @RequestParam(name = "projectEndDate") String projectEndDate,
                                          @RequestParam(name = "projectHours") Integer projectHours,
                                          @RequestParam(name = "projectDesc") String projectDesc,
                                          HttpSession session) throws BusinessException {
        UserModel userModel=(UserModel) session.getAttribute("LOGIN_USER");
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        ProjectModel model=projectService.getProjectByCode(projectCode);
        //项目的代号是唯一的
        if(model!=null){
            throw new BusinessException(EmBusinessError.PROJECT_EXIST);
        }
        ProjectModel projectModel=new ProjectModel();
        projectModel.setProjectName(projectName);
        projectModel.setProjectCode(projectCode);
        projectModel.setProjectPriority(projectPriority);
        projectModel.setProjectKeyword(projectKeyword);
        //将前端的日期转化成joda可以处理的类型
        projectModel.setProjectStartDate(new DateTime(projectStartDate.replace(" ","T")));
        projectModel.setProjectEndDate(new DateTime(projectEndDate.replace(" ","T")));
        projectModel.setHours(projectHours);
        projectModel.setProjectDesc(projectDesc);
        projectModel.setProjectCreater(userModel.getUsername());
        //默认的项目都是未开始的
        projectModel.setProjectStatus("未开始");
        projectService.createProject(projectModel);
        return CommonReturnType.create(null);
    }

    //获取项目列表,开启分页功能
    @RequestMapping(value = "/list",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listProject(@RequestParam(name = "page") Integer page,
                                        @RequestParam(name = "limit") Integer limit,
                                        HttpSession session){
        //开启分页
        Page tmpPage=PageHelper.startPage(page,limit);
        UserModel userModel=(UserModel)session.getAttribute("LOGIN_USER");
        List<ProjectModel> projectModelList=projectService.listProject();
        List<ProjectVO> projectVOList=projectModelList.stream().map(projectModel -> {
            ProjectVO projectVO=this.convertVOFromModel(projectModel);
            if(userModel!=null) {
                projectVO.setRole(userModel.getRole());
            }
            return projectVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(projectVOList,tmpPage.getTotal());
    }

    //获取项目列表,不开启分页功能
    @RequestMapping(value = "/code",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType listProjectCode(){
        //开启分页
        List<ProjectModel> projectModelList=projectService.listProject();
        List<ProjectVO> projectVOList=projectModelList.stream().map(projectModel -> {
            ProjectVO projectVO=new ProjectVO();
            projectVO.setProjectCode(projectModel.getProjectCode());
            return projectVO;
        }).collect(Collectors.toList());
        return CommonReturnType.create(projectVOList);
    }

    //更新项目
    @RequestMapping(value = "/update",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType updateProject(@RequestParam(name = "projectCode_edit") String projectCode,
                                          @RequestParam(name = "projectPriority_edit") String projectPriority,
                                          @RequestParam(name = "projectStartDate_edit") String projectStartDate,
                                          @RequestParam(name = "projectEndDate_edit") String projectEndDate,
                                          @RequestParam(name = "projectHours_edit") Integer projectHours,
                                          @RequestParam(name = "projectDesc_edit") String projectDesc) throws BusinessException {
        ProjectModel projectModel=projectService.getProjectByCode(projectCode);
        if(projectCode==null){
            throw new BusinessException(EmBusinessError.PROJECT_NOT_EXIST);
        }
        projectModel.setProjectPriority(projectPriority);
        projectModel.setProjectStartDate(new DateTime(projectStartDate.replace(" ","T")));
        projectModel.setProjectEndDate(new DateTime(projectEndDate.replace(" ","T")));
        projectModel.setHours(projectHours);
        projectModel.setProjectDesc(projectDesc);
        System.out.println("projectModel.getProjectStartDate() = " + projectModel.getProjectStartDate());
        System.out.println("projectModel.getProjectEndDate() = " + projectModel.getProjectEndDate());
        boolean result=projectService.updateProject(projectModel);
        if(!result){
            throw new BusinessException(EmBusinessError.PROJECT_UPDATE_FAIL);
        }
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/delete",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType deleteProject(@RequestParam(name = "id") Integer projectId) throws BusinessException {
        ProjectModel projectModel=projectService.getProjectById(projectId);
        if(projectModel==null){
            throw new BusinessException(EmBusinessError.PROJECT_NOT_EXIST);
        }
        boolean result=projectService.deleteProject(projectId);
        if(!result){
            throw new BusinessException(EmBusinessError.PROJECT_DELETE_FAIL);
        }
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/start",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType startProject(@RequestParam(name = "projectStartDate") String projectStartDate,
                                         @RequestParam(name = "projectCode") String projectCode) throws BusinessException {
        ProjectModel projectModel=projectService.getProjectByCode(projectCode);
        if(projectModel==null){
            throw new BusinessException(EmBusinessError.PROJECT_NOT_EXIST);
        }
        //点击开始后，将项目的状态设置为进行中，并用当前的时间重置项目原有的开始时间
        projectModel.setProjectStatus("进行中");
        projectModel.setProjectStartDate(new DateTime(projectStartDate.replace(" ","T")));
        boolean result=projectService.updateProject(projectModel);
        if(!result){
            throw new BusinessException(EmBusinessError.PROJECT_UPDATE_FAIL);
        }
//        System.out.println("nowDate = " + projectStartDate);
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/finish",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FORMAT})
    @ResponseBody
    public CommonReturnType finishProject(@RequestParam(name = "projectEndDate") String projectEndDate,
                                         @RequestParam(name = "projectCode") String projectCode) throws BusinessException {
        ProjectModel projectModel=projectService.getProjectByCode(projectCode);
        if(projectModel==null){
            throw new BusinessException(EmBusinessError.PROJECT_NOT_EXIST);
        }
        //点击开始后，将项目的状态设置为进行中，并用当前的时间重置项目原有的开始时间
        projectModel.setProjectStatus("已完成");
        projectModel.setProjectEndDate(new DateTime(projectEndDate.replace(" ","T")));
        boolean result=projectService.updateProject(projectModel);
        if(!result){
            throw new BusinessException(EmBusinessError.PROJECT_UPDATE_FAIL);
        }
//        System.out.println("nowDate = " + projectStartDate);
        return CommonReturnType.create(null);
    }
}
